package cn._2dland.servlet;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import cn._2dland.tools.DamnServlet;
import cn._2dland.utils.HttpUtils;

public class SixRoomsServlet extends HttpServlet {
	private static final long serialVersionUID = -2688100110266658656L;
	
	private static final String SIXROOMS_URL = "http://6.cn/v72.php?vid=";

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String referrer = req.getHeader("Referer");

		String duration = "";
		String videoUrl = "";
		try {
			String vid = req.getParameter("vid");
			if(vid == null || "".equals(vid))
				throw new Exception("无效vid！");

			if(referrer == null) {
				// 读取远程XML
				Document doc = HttpUtils.getHTTPXMLDocument(SIXROOMS_URL + vid);
				// 读取视频信息
				Element root = doc.getDocumentElement();
				Element video = (Element)root.getElementsByTagName("VIDEO").item(0);
				// 获取长度
				Element l = (Element)video.getElementsByTagName("l").item(0);
				long dur = Long.parseLong(l.getFirstChild().getNodeValue());
				duration = String.valueOf(dur * 1000);
				// 获取地址
				Element file = (Element)video.getElementsByTagName("file").item(0);
				videoUrl = file.getFirstChild().getNodeValue();
				// 计算实际地址
				videoUrl = getVideoURL(videoUrl);
			} else {
				videoUrl = new StringBuffer(DamnServlet.DAMN_API_URL).append("?src=6cn&vid=").append(vid).toString();
				duration = "0";
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			videoUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/parse_failed.flv";
			duration = "5022";
		}

		StringBuffer infoXml = new StringBuffer();
		infoXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"  standalone=\"no\"?>");
		infoXml.append("<video>");
		infoXml.append("<dur>").append(duration).append("</dur>");
		infoXml.append("<url><![CDATA[").append(videoUrl).append("]]></url>");
		infoXml.append("</video>");

		resp.setContentType("text/xml; charset=UTF-8");
		resp.setCharacterEncoding("utf-8");
		resp.getWriter().print(infoXml);
	}
	
	private String getVideoURL(String url) {
		long utcSeconds = System.currentTimeMillis() / 1000;
		utcSeconds += 123456;
		Random rnd = new Random();
		long key1 = 0;
		long key2 = 0;
		long key3 = 1000000000 + rnd.nextInt(1000000000);
		long key4 = 1000000000 + rnd.nextInt(1000000000);
		
		int keyMode = rnd.nextInt(100);
		if(keyMode > 50) {
			key1 = Math.abs((long)Math.floor(utcSeconds / 3) ^ key3);
			key2 = Math.abs((long)Math.floor(utcSeconds * 2 / 3) ^ key4);
		}
		else {
			key1 = Math.abs((long)Math.floor(utcSeconds * 2 / 3) ^ key3);
			key2 = Math.abs((long)Math.floor(utcSeconds / 3) ^ key4);
		}
		String flvURL = url + "?key1=" + key1 + "&key2=" + key2 + "&key3=" + key3 + "&key4=" + key4;

		return flvURL;
	}
}
